import React, { Component } from 'react'
import { Card, Button, Table, Modal, message,  } from 'antd'
import {reqRoleList} from '../../api/api'
import AddRole from './add-role'
import AuthForm from './auth-form'
import {reqAddRoleList, reqUpdateRole} from '../../api/api'
import memoryUtils from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'
import withRouter from '../../utils/withRouter'
import dayjs from 'dayjs'

class Role extends Component {

  auth = React.createRef()

  state = {
    roles: [], // 所有角色列表
    role: {}, // 选中的
    isShowAdd:0,
    isShowAuth: 0
  }

  initColumns = () => {
    this.columns = [
      {
        title: '角色名称',
        dataIndex: 'name'
      },
      {
        title: '创建时间',
        render: (role) => {return dayjs(role.create_time).format('DD/MM/YYYY')}
      },
      {
        title: '授权时间',
        render: (role) => {return dayjs(role.auth_time).format('DD/MM/YYYY')}
      },
      {
        title: '授权人',
        dataIndex: 'auth_name'
      }
    ]
  }

  // 获取角色列表
  getRoleList = async () => {
    const result = await reqRoleList ()
    if (result.status === 0) {
      const roles = result.data
      this.setState ({roles})
    }
  }

  onRow = (role) => {
    return {
      onClick: event => {
        // console.log (role)
        this.setState ({role})
      }
    }
  }

  // 添加角色————————————————————————————————————————————
  addRoleModal = () => {
    this.setState ({isShowAdd: 1})
  }
  handleAddOk = () => {
    // 表单验证  收集数据 请求添加  结果提示 展示列表
    this.form.current.resetFields ()
    this.form.current.validateFields ().then (async (values) => {
      console.log ('成功', values)
      const {roleName} = values
      const result = await reqAddRoleList (roleName)
      console.log (result)
    }).catch ((err) => {
      // console.log (err)
      // message.error (err.errorFields[0].errors)
    })
  }

  handleCancel = () => {
    // 清除数据
    this.form.current.resetFields ()
    this.setState({ isShowAdd: 0 })
  }

  // 设置权限————————————————————————————
  updateAuth = () => {
    this.setState ({isShowAuth: 1})
  }

  handleUpdate = async () => {
    const role = this.state.role
    // 得到更新后的选中menus
    const menus = this.auth.current.getMenus ()
    role.menus = menus
    role.auth_name = memoryUtils.user.username
    this.setState ({isShowAuth: 0})
    const result = await reqUpdateRole (role)
    if (result.status === 0) {
      // 如果更新的是自己角色权限，强制退出
      if (role._id === memoryUtils.user.role_id) {
        message.success ('设置当前用户权限成功，请重新登录')
        memoryUtils.user ={}
        storageUtils.removeUser ()
        this.props.navigate ('/login')
      } else {
        message.success ('设置权限成功')
        this.getRoleList ()
      }
    }
  }

  updateCancel = () => {
    this.setState ({isShowAuth: 0})
  }
 

  UNSAFE_componentWillMount () {
    this.initColumns ()
  }

  componentDidMount () {
    this.getRoleList ()
  }

  render() {

    const {roles, role, isShowAdd, isShowAuth} = this.state

    const title = (
      <span>
        <Button type='primary' onClick={this.addRoleModal}>创建角色</Button> &nbsp;
        <Button type='primary' disabled={!role._id} onClick={this.updateAuth}>设置权限</Button>
      </span>
    )
    return (
      <Card title={title}>
        <Table
        bordered
        sticky
        dataSource={roles}
        columns={this.columns}
        rowKey='_id'
        rowSelection={{
          type: 'radio', 
          selectedRowKeys: [role._id], 
          onSelect: (role) => {this.setState({role})}
        }}
        pagination={{ defaultPageSize: 8, showQuickJumper: true }}
        onRow={this.onRow}>
        </Table>

        <Modal title="添加角色" visible={isShowAdd === 1} onOk={this.handleAddOk} onCancel={this.handleCancel}>
          <AddRole  addform={form => this.form = form}/>
        </Modal>

        <Modal title="设置角色权限" visible={isShowAuth === 1} onOk={this.handleUpdate} onCancel={this.updateCancel}>
          <AuthForm  role={role} ref={this.auth}/>
        </Modal>
      </Card>
    )
  }
}

export default withRouter (Role)
